package com.weixinadmin.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;

import com.weixinadmin.dao.CustomerGroupSql;
import com.weixinadmin.dao.CustomerGroupdao;
import com.weixindamin.exception.wxexception;

public class CustomerGrouphttp  {
	 private static Logger logger = Logger.getLogger(CustomerGrouphttp.class);//log4j
		
	//https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID
	
	private String creategroupurl = "https://api.weixin.qq.com/cgi-bin/groups/create?";
	private String customerinfourl = "https://api.weixin.qq.com/cgi-bin/user/info?";
	
	public String httpcreategroup(String groupname) throws wxexception{
		//https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
		
		String token = new Token().gettoken();	
		if(token == null){
			// throw Exception
			return null;
		}
		HttpPool httppool = new HttpPool();		
		return httppool.httppost(creategroupurl+"access_token="+token,"{\"group\":{\"name\":\""+groupname+"\"}}\"");
			
	}
	
	/*
	public CustomerGroupdao getcustomergroup(){
		String jsonstr = httpgetcustomerinfo(openid);
		//String jsongroup = null;//httpgetcustomerinfo(openid);
		
		if(null == jsonstr){
			return null;
		}
		
		com.weixinadmin.dao.Customerdao custmer = null;
		JSONObject json = JSONObject.fromObject(jsonstr);
		
		try{
			custmer =  new com.weixinadmin.dao.Customerdao();
			custmer.setcity(json.getString("city"));
			custmer.setcountry(json.getString("country"));
			custmer.setheadimgurl(json.getString("headimgurl"));
			custmer.setlanguage(json.getString("language"));
			custmer.setnickname(json.getString("nickname"));
			custmer.setopenid(json.getString("openid"));
			custmer.setprovince(json.getString("province"));
			custmer.setsex(json.getInt("sex"));
			custmer.setsubscribe(json.getInt("subscribe_time"));
			Timestamp tt = new Timestamp(json.getInt("subscribe_time"));
			custmer.setsubscribetime(tt);
			//System.out.println("subscribe_time:　"+ json.getInt("subscribe_time"));			
		}catch (Exception e) {
			e.printStackTrace();	  
		} finally {
			return custmer;
		}
	
	}
	/**/
	
	public String httpgetcustomergroup(String openid) throws wxexception{
		String token = new Token().gettoken();	
		if(token == null){
			// throw Exception
			return null;
		}
		HttpPool httppool = new HttpPool();			
		//String httpresult; 
//		System.out.println(openidlisturl+"access_token="+token+"&next_openid="+openid);		
		return httppool.httppost("https://api.weixin.qq.com/cgi-bin/groups/getid?"+"access_token="+token,"{\"openid\":\""+openid + "\"");
	}
	
	public int getcustomergroup(String openid) throws wxexception{
		String jsonstr = httpgetgrouplist();
		
		if(null == jsonstr){
			return 0;
		}
		JSONObject json = JSONObject.fromObject(jsonstr);
		//System.out.println("org:　"+nn);
			
		return json.getInt("groupid");
	}
	
	public void changegroupname(int id,String name){
		
	}
	public String httpgetgrouplist() throws wxexception{
		String token = new Token().gettoken();	
		if(token == null){
			// throw Exception
			return null;
		}
		HttpPool httppool = new HttpPool();			
		//String httpresult; 
//		System.out.println(openidlisturl+"access_token="+token+"&next_openid="+openid);		
		return httppool.httpget("https://api.weixin.qq.com/cgi-bin/groups/get?"+"access_token="+token);
	 }
	 
	public List<CustomerGroupdao> getgrouplist() throws wxexception{
		String jsonstr = httpgetgrouplist();
		List<CustomerGroupdao> groups = new ArrayList();
		
		if(null == jsonstr){
			return null;
		}
		JSONObject json = JSONObject.fromObject(jsonstr);
		//System.out.println("org:　"+nn);
		try{
			
				JSONArray jsonArr = JSONArray.fromObject(json.getString("groups"));
				for(int i = 0; i < jsonArr.size(); i++){
				CustomerGroupdao cgd = new CustomerGroupdao();
				cgd.setname(jsonArr.getJSONObject(i).getString("name"));
				cgd.setid(jsonArr.getJSONObject(i).getInt("id"));
				cgd.setcount(jsonArr.getJSONObject(i).getInt("count"));				
				groups.add(cgd);		
			logger.info("cgd:　"+ cgd.toString());		
				}	
		}
		catch (Exception e) {
			e.printStackTrace();	  
		} finally {
			return groups;
		}
	
		 
	}
	
			
	 public static void main(String[] args) throws wxexception  
	 {  
		 new CustomerGrouphttp().httpcreategroup("gzytest");
		 new CustomerGrouphttp().getgrouplist();
		 
	 }
	 public void jsontest(){
			String ss = "{"+
			    "\"subscribe\": 1,\n"+ 
			    "\"openid\": \"o6_bmjrPTlm6_2sgVt7hMZOPfL2M\",\n"+ 
			    "\"nickname\": \"Band\",\n"+ 
			    "\"sex\": 1,\n"+ 
			    "\"language\": \"zh_CN\",\n"+ 
			    "\"city\": \"广州\",\n"+ 
			    "\"province\": \"广东\",\n"+ 
			    "\"country\": \"中国\",\n"+ 
			    "\"headimgurl\":    \"http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0\",\n"+ 
			   "\"subscribe_time\": 1382694957\n"+
			   	"}";
			JSONObject json = JSONObject.fromObject(ss);
			System.out.println("org:　"+ss);
			try{
				//access_token = json.getString("access_token");
				System.out.println("openid:　"+ json.getString("openid"));
				System.out.println("sex:　"+ json.getInt("sex"));
				System.out.println("subscribe_time:　"+ json.getInt("subscribe_time"));			
			}catch (Exception e) {
				e.printStackTrace();	  
			} finally {
				return ;
			}
		}
	 public void jsontest2(){
		 	String ss = "{\"total\":2,\"count\":2,\"data\":{\"openid\":[\"\",\"OPENID1\",\"OPENID2\"]},\"next_openid\":\"NEXT_OPENID\"}";
		 	String nn = "{\"total\":2,\"count\":2,\"data\":{\"openid\":[\"\",\"OPENID1\",\"OPENID2\"]},\"next_openid\":\"\"}";
			
		 	JSONObject json = JSONObject.fromObject(nn);
			System.out.println("org:　"+nn);
			try{
				//access_token = json.getString("access_token");
				String objnull = null;
				System.out.println("count:　"+ json.getInt("count"));
				System.out.println("total:　"+ json.getInt("total"));			
				System.out.println("next_openid:　"+ json.getString("next_openid"));
				if(json.getString("next_openid").equals(""))
					System.out.println("next_openid :  ");	
				System.out.println("data:　"+ json.getString("data"));		
				JSONObject jsondata = JSONObject.fromObject(json.getString("data"));				
				JSONArray array = JSONArray.fromObject(jsondata.getString("openid"));
				//Object[] obj = new Object[array.size()];
				for(int i = 0; i < array.size(); i++){
				//JSONValue jsonObject = array.getJSONObject(i);
				String obj = (String)array.get(i);
				if(null == obj)
					System.out.println("null :　"+i);						
				
				System.out.println("num　"+i+" : "+ obj.toString());						
				} 
			}catch (Exception e) {
				e.printStackTrace();	  
			} finally {
				return ;
			}
		}
		 
}
